<?php
if (!defined('__TYPECHO_ROOT_DIR__'))
    exit;

class TeacherLogin_Action extends Typecho_Widget
{

    /* 重置当前用户绑定数据 */
    public function reset()
    {
        require_once __TYPECHO_ROOT_DIR__ . __TYPECHO_ADMIN_DIR__ . 'common.php';
        $res = new Typecho_Response();
        $ret = array();

        if ($user->haslogin()) {
            // 获取当前用户名
            $name = $user->__get('name');

            // 获取插件配置
            $options = TeacherLogin_Plugin::getoptions();
            $key = $options->key;

            // 处理数据
            $filepath = TeacherLogin_Plugin::PLUGIN_PATH . $key . '.db';
            $data = TeacherLogin_Plugin::getuser();

            $data[$name]['wx'] = '';
            $data[$name]['qq'] = '';
            $data[$name]['wechat_work'] = '';

            @file_put_contents($filepath, TeacherLogin_Plugin::authcode(serialize($data), 'ENCODE', $key));
            $ret['code'] = 200;
            $ret['msg'] = '当前用户绑定信息重置成功';
        } else {
            $ret['msg'] = 'what are you doing?';
        }
        $res->throwJson($ret);
    }

    /* 跳转验证登录 */
    public function login()
    {
        $req = new Typecho_Request();
        $res = new Typecho_Response();
        $token = base64_decode(urldecode($req->get('token')));
        // 获取插件配置
        $options = Helper::options()->plugin(TeacherLogin_Plugin::PLUGIN_NAME);
        $key = $options->key;

        // 解密Token
        $data = @json_decode(TeacherLogin_Plugin::authcode($token, 'DECODE', $key), true);

        $user_qr = TeacherLogin_Plugin::getuser();
        if (is_array($data) && isset($data) && $user_qr[$data['user']][$data['type']] == $data['uin'] && time() < $data['time']) {
            $hashValidate = true;
        }

        $name = $data['user'];
        $db = Typecho_Db::get();

        $user = $db->fetchRow($db->select()
            ->from('table.users')
            ->where((strpos($name, '@') ? 'mail' : 'name') . ' = ?', $name)
            ->limit(1));
        if ($user && $hashValidate) {
            $authCode = function_exists('openssl_random_pseudo_bytes') ?
                bin2hex(openssl_random_pseudo_bytes(16)) : sha1(Typecho_Common::randString(20));
            $user['authCode'] = $authCode;

            Typecho_Cookie::set('__typecho_uid', $user['uid'], $expire);
            Typecho_Cookie::set('__typecho_authCode', Typecho_Common::hash($authCode), $expire);

            //更新最后登录时间以及验证码
            $db->query($db
                ->update('table.users')
                ->expression('logged', 'activated')
                ->rows(array('authCode' => $authCode))
                ->where('uid = ?', $user['uid']));

            /** 压入数据 */
            $this->push($user);
            $this->_user = $user;
            $this->_hasLogin = true;
            echo 'success';
        }
        $res->redirect(Helper::options()->adminUrl);
    }

    /* 二维码授权绑定 */
    public function authbind()
    {
        $path = TeacherLogin_Plugin::PLUGIN_PATH . 'views/authbind.php';
        require_once $path;
    }

    /* 获取登录二维码 */
    public function getqrcode()
    {
        $res = new Typecho_Response();
        $qr = json_decode(self::get_curl('https://wj.qq.com/api/session/authorization/create_token', [
            'post' => "教书先生"
        ]), true);
        if ($qr['status'] === 1) {
            $ret = [
                'code' => 200,
                'token' => $qr['data']['token'],
                'qr_url' => 'https://wj.qq.com/api/session/authorization?token=' . $qr['data']['token'] . '&scene_type=user'
            ];
        } else {
            $ret = [
                'code' => 500
            ];
        }
        $res->throwJson($ret);
    }

    /* 获取登录结果 */
    public function getresult()
    {
        $res = new Typecho_Response();
        $req = new Typecho_Request();
        $ret = array();
        $token = $req->get('token');
        $login = $req->get('login');
        if ($token) {
            $result = self::get_curl('https://wj.qq.com/api/session/authorization/check_token?token=' . $token . '&scene_type=user', [
                'GetCookie' => 1
            ]);
            $body = json_decode($result['body'], true);
            if ($body['data']['code'] == 3) {
                $cookie_wj = '';
                foreach ($result['Cookie'][1] as $value) {
                    if (strpos($value, 'session_user') !== false) {
                        $cookie_wj = $value;
                    }
                }
                $session = json_decode(self::get_curl('https://wj.qq.com/api/account', ['cookie' => $cookie_wj]), true);
                $ret['code'] = 3;
                $ret['data']['uin'] = $session['data']['user_id'];
                $ret['data']['type'] = $session['data']['user_type'];
            } else {
                $ret = [
                    'code' => $body['data']['code']
                ];
            }
        } else {
            $ret['code'] = 500;
            $ret['msg'] = '请求参数错误，请刷新重试！~~';
        }
        // ------------------------
        if ($login && $ret['code'] == 3) { //验证登录
            // 获取插件配置
            $options = TeacherLogin_Plugin::getoptions();
            $key = $options->key;
            // 处理数据
            $filepath = TeacherLogin_Plugin::PLUGIN_PATH . $key . '.db';
            $data = unserialize(TeacherLogin_Plugin::authcode(file_get_contents($filepath), 'DECODE', $key));

            $ret['login']['msg'] = 'Fail';
            $ret['login']['code'] = 0;
            foreach ($data as $user => $arr) {
                if ($arr[$ret['data']['type']] == $ret['data']['uin']) {
                    // 生成登录有效地址
                    $time = time() + 15; //  URL失效时间
                    $token = TeacherLogin_Plugin::authcode(json_encode(array('user' => $user, 'time' => $time, 'type' => $ret['data']['type'], 'uin' => $ret['data']['uin'])), 'ENCODE', $key);

                    $ret['login']['token'] = base64_encode($token);
                    $ret['login']['code'] = 10000;
                    $ret['login']['user'] = $user;
                    $ret['login']['msg'] = 'Success';
                    $ret['login']['url'] = TeacherLogin_Plugin::tourl('TeacherLogin/login');
                    break;
                }
            }
        }
        $res->throwJson($ret);
    }

    /* 绑定授权信息 */
    public function bind()
    {
        require_once __TYPECHO_ROOT_DIR__ . __TYPECHO_ADMIN_DIR__ . 'common.php';
        $res = new Typecho_Response();
        $req = new Typecho_Request();
        $ret = array();

        if ($user->haslogin()) {
            // 获取当前用户名
            $name = $user->__get('name');

            // 获取插件配置
            $options = TeacherLogin_Plugin::getoptions();
            $key = $options->key;

            // 获取请求参数
            $type = $req->get('type');
            $uin = $req->get('uin');

            // 处理数据
            $filepath = TeacherLogin_Plugin::PLUGIN_PATH . $key . '.db';
            $data = TeacherLogin_Plugin::getuser();

            // 判断当前UIN是否已经绑定
            foreach ($data as $name_ => $arr) {
                if ($arr[$type] == $uin && $name_ != $name) {
                    $ret['code'] = 201;
                    $ret['msg'] = '此账号已绑定另一账户，绑定失败';
                    $res->throwJson($ret);
                    break;
                }
            }
            $data[$name][$type] = $uin;
            @file_put_contents($filepath, TeacherLogin_Plugin::authcode(serialize($data), 'ENCODE', $key));
            $ret['code'] = 200;
            if ($type == "wx") {
                $jsxs = "微信";
            } elseif ($type == "qq") {
                $jsxs = "QQ";
            } else {
                $jsxs = "企业微信";
            }
            $ret['msg'] = ($jsxs) . '绑定成功';
        } else {
            $ret['msg'] = 'what are you doing?';
        }
        $res->throwJson($ret);
    }


    /** Curl单例封装函数 */
    public static function get_curl($url, $paras = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if (isset($paras['Header'])) {
            $Header = $paras['Header'];
        } else {
            $Header[] = "Accept:*/*";
            $Header[] = "Accept-Encoding:gzip,deflate,sdch";
            $Header[] = "Accept-Language:zh-CN,zh;q=0.8";
            $Header[] = "Connection:close";
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $Header);
        if (isset($paras['ctime'])) { // 连接超时
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $paras['ctime']);
        } else {
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        }
        if (isset($paras['rtime'])) { // 读取超时
            curl_setopt($ch, CURLOPT_TIMEOUT, $paras['rtime']);
        }
        if (isset($paras['post'])) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $paras['post']);
        }
        if (isset($paras['header'])) {
            curl_setopt($ch, CURLOPT_HEADER, true);
        }
        if (isset($paras['cookie'])) {
            curl_setopt($ch, CURLOPT_COOKIE, $paras['cookie']);
        }
        if (isset($paras['refer'])) {
            if ($paras['refer'] == 1) {
                curl_setopt($ch, CURLOPT_REFERER, 'http://m.qzone.com/infocenter?g_f=');
            } else {
                curl_setopt($ch, CURLOPT_REFERER, $paras['refer']);
            }
        }
        if (isset($paras['ua'])) {
            curl_setopt($ch, CURLOPT_USERAGENT, $paras['ua']);
        } else {
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
        }
        if (isset($paras['nobody'])) {
            curl_setopt($ch, CURLOPT_NOBODY, 1);
        }
        curl_setopt($ch, CURLOPT_ENCODING, "gzip");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if (isset($paras['GetCookie'])) {
            curl_setopt($ch, CURLOPT_HEADER, 1);
            $result = curl_exec($ch);
            preg_match_all("/Set-Cookie: (.*?);/m", $result, $matches);
            $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            $header = substr($result, 0, $headerSize); //状态码
            $body = substr($result, $headerSize);
            $ret = [
                "Cookie" => $matches, "body" => $body, "header" => $header, 'code' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
            ];
            curl_close($ch);
            return $ret;
        }
        $ret = curl_exec($ch);
        if (isset($paras['loadurl'])) {
            $Headers = curl_getinfo($ch);
            if (isset($Headers['redirect_url'])) {
                $ret = $Headers['redirect_url'];
            } else {
                $ret = false;
            }
        }
        curl_close($ch);
        return $ret;
    }

}